// imrc
import React, { Component,createRef } from 'react';
// ccc
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      list:[
        {title:"学习Vue",done:true,state:1},
        {title:"学会大王者",done:false,state:1}
      ]
     }
     this.myref = createRef();
  }
  addList = ()=>{
    // 获取现有状态list
    var list = this.state.list;
    // 添加一项，内容为input表单的值
    list.unshift( {title:this.myref.current.value,done:false,state:1})
    // 更新state
    this.setState({list})
    // 清空文本框
    this.myref.current.value = "";
  }
  delList = (item)=>{
    // 获取现有的状态list
    var list = this.state.list;
    // 根据item的title查出在list列表是第几个
    var ind = list.findIndex(value=>value.title===item.title);
    // 删除1个
    list.splice(ind,1);
    // 更新state的list值同时自动更新视图
    this.setState({list})
  }
  updateList = (item)=>{
    // 获取现有的状态list
    var list = this.state.list;
    // 根据item的title查出在list列表是第几个
    var ind = list.findIndex(value=>value.title===item.title);
    // 把done取帆
    list[ind].done = !list[ind].done
    // 更新state的list值同时自动更新视图
    this.setState({list})
  }
  render() { 
    // filter遍历并过滤数组，当回调函数返回真保留
    var doneList = this.state.list.filter(item=>item.done)
    var undoneList = this.state.list.filter(item=>!item.done)
    return ( <div>
      <h1>美妙清单</h1>
      <input ref={this.myref}/><button onClick={this.addList}>添加</button>
      <h3>未完成({undoneList.length})</h3>
      <div>
        {undoneList.map((item,index)=><div key={index}>
          <input checked={item.done} onChange={()=>{this.updateList(item)}} type="checkbox"/>
          <span>
            <span>{item.title}</span>
          </span>
          <button onClick={()=>this.delList(item)}>x</button>
        </div>)}
      </div>
      <h3>已完成({doneList.length})</h3>
      <div>
        {/* 对已完成列表进行遍历，映射为一个div */}
        {/* 这里的item 指的是：{title:"学习Vue",done:true,state:1} */}
        {doneList.map((item,index)=><div key={index}>
          {/* 包含了一个多选框，checked值和遍历元素item的done值保持一致 */}
          <input checked={item.done}  onChange={()=>{this.updateList(item)}} type="checkbox" />
          <span>
            {/* 渲染标题 */}
            <span>{item.title}</span>
          </span>
          {/* 添加删除按钮 */}
          <button onClick={()=>this.delList(item)}>x</button>
        </div>)}
      </div>
    </div> );
  }
}
 
export default App;